#!/usr/bin/python3
#拒绝ssh攻击， 实时读取/var/log/secure 日志， 发现攻击， 立刻列入/etc/hosts.deny的拒绝清单
import time
import time,datetime
import requests,json
#from bs4 import BeautifulSoup
def location_(ip):
    url='https://ip.cn/api/index?ip={}&type=1'.format(ip)
    r = requests.get(url, timeout=5)
    r.encoding='utf-8'
    #print(r)

    #soup = BeautifulSoup(r.text, 'lxml')
    return json.loads(r.text)['address']

def write_a(ip):
    now='##'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    ip=ip.replace('\n','')
    if ip=='':
        pass
    elif len(ip)<9:
        pass
    else:
        with open('/etc/hosts.deny','a')as f:
#            print(f.readlines())
            location1=location_(ip)
            f.write('sshd:{}\n{} {}\n'.format(ip,now,location1))


def deal(line):
    print(line)
    if "Invalid" in line:
        ip=(line.split(' ')[10])
        print(line.split(' ')[10])
#        print('********', line)
        write_a(ip)
    elif 'Failed password' in line:
#        print(line)
        ip=(line.split(' ')[10])
        print(ip)
        write_a(ip)
    elif 'rhost' in line:
        #pass
        ip=(line.split(' ')[13][6:])
        print(ip)
        #print(line)
        write_a(ip)
    elif 'error' in line or 'refused' in line:
        pass
    elif 'Disconnected' in line:
        ip=(line.split(' ')[8])
        print('Disconnect',ip)
#        write_a(ip)
    elif 'disconnect' in line:
        ip=(line.split(' ')[9])
        print('disconnect',ip)
        write_a(ip)
    elif 'warning' in line:
        pass
    else:
#        print('nnnnnnnnnnnn',line)
        pass

with open('/var/log/secure','r')as f:
    f.seek(0,2)
    while True:
        time.sleep(1)
#        print(f.tell())
        line=f.readline()
        if line:
            print(line)
            deal(line)
